package top.andnux.memoryleak.case2_handler;

import androidx.appcompat.app.AppCompatActivity;
import top.andnux.memoryleak.R;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import java.lang.ref.WeakReference;

public class HandlerActivity extends AppCompatActivity {

    private MyHandler mHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.a_handler);
        mHandler = new MyHandler(this);
        mHandler.sendEmptyMessageDelayed(0x10, 1000 * 20);
        this.finish();
    }

    @Override
    protected void onDestroy() {
        //第三步清理回收工作
        mHandler.removeMessages(0x10);
        mHandler = null;
        super.onDestroy();
    }

    //第一步声明静态Handler
    private static class MyHandler extends Handler {
        //第二步使用软引用。
        private WeakReference<HandlerActivity> mReference;

        public MyHandler(HandlerActivity activity) {
            mReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    }
}
